import React, { useState, useEffect, Fragment } from 'react';
import { Form, Input, DatePicker, Select, Radio, Divider, message } from 'antd';
import cn from 'classnames';
// import clone from 'lodash/clone';
import moment from 'moment';
import { getOrganization } from '@/utils/utils';
import { FormContainer } from '@/components/UserForm';
import {
    jsonFormWork,
    jsonFormFamily,
    jsonFormSchool,
    jsonFormTrain,
    jsonFormAward,
    map
} from '@/pages/InitUser/jsonForm';
import styles from './index.less';

const formItemLayout = {
    labelCol: {
        md: { span: 8 },
        xs: { span: 24 },
        sm: { span: 24 }
    },
    wrapperCol: {
        md: { span: 15 },
        xs: { span: 24 },
        sm: { span: 24 }
    }
};

const formItemLayout2 = {
    labelCol: {
        md: { span: 4 },
        xs: { span: 24 },
        sm: { span: 24 }
    },
    wrapperCol: {
        md: { span: 7 },
        xs: { span: 24 },
        sm: { span: 24 }
    }
};
const { RangePicker, MonthPicker } = DatePicker;
const { Option } = Select;

let initFamilyKey = 0;
let initWorkKey = 0;
let initSchoolKey = 0;
let initTrainKey = 0;
let initAwardKey = 0;

const AddForm = ({ form, dict, user, userCode, formData, isDisabled }) => {
    const { getFieldDecorator } = form;

    const [familyKeys, setFamilyKeys] = useState([initFamilyKey]);
    const [workKeys, setWorkKeys] = useState([initWorkKey]);
    const [schoolKeys, setSchoolKeys] = useState([initSchoolKey]);
    const [trainKeys, setTrainKeys] = useState([initTrainKey]);
    const [awardKeys, setAwardKeys] = useState([initAwardKey]);

    const [removeFamilyIds, setRemoveFamilyIds] = useState([]);
    const [removeWorkIds, setRemoveWorkIds] = useState([]);
    const [removeSchoolIds, setRemoveSchoolIds] = useState([]);
    const [removeTrainIds, setRemoveTrainIds] = useState([]);
    const [removeAwardIds, setRemoveAwardIds] = useState([]);

    getFieldDecorator('familyKeys', { initialValue: [0] }); // 用于保存keys的字段，方便外面可以取之到keys
    getFieldDecorator('workKeys', { initialValue: [0] });
    getFieldDecorator('schoolKeys', { initialValue: [0] });
    getFieldDecorator('trainKeys', { initialValue: [0] });
    getFieldDecorator('awardKeys', { initialValue: [0] });

    getFieldDecorator('removeFamilyIds', { initialValue: [] }); // 维护dto里被删的id项
    getFieldDecorator('removeWorkIds', { initialValue: [] });
    getFieldDecorator('removeSchoolIds', { initialValue: [] });
    getFieldDecorator('removeTrainIds', { initialValue: [] });
    getFieldDecorator('removeAwardIds', { initialValue: [] });

    const returnDefinedAreaCode = () => (getOrganization(user.companyId)?.area === 'cn' ? '86' : '65');

    const getArrKeys = (arr = []) => {
        const array = [];
        arr.forEach((_ele, index) => {
            array.push(index);
        });
        return array;
    };
    useEffect(() => {
        if (formData.familyDTOList && formData.familyDTOList.length) {
            initFamilyKey = formData.familyDTOList.length > 0 ? formData.familyDTOList.length - 1 : 0;
            setFamilyKeys(getArrKeys(formData.familyDTOList));
            form.setFieldsValue({
                familyKeys: getArrKeys(formData.familyDTOList)
            });
        }
        if (formData.workDTOList && formData.workDTOList.length) {
            initWorkKey = formData.workDTOList.length > 0 ? formData.workDTOList.length - 1 : 0;
            setWorkKeys(getArrKeys(formData.workDTOList));
            form.setFieldsValue({
                workKeys: getArrKeys(formData.workDTOList)
            });
        }
        if (formData.schoolDTOList && formData.schoolDTOList.length) {
            initSchoolKey = formData.schoolDTOList.length > 0 ? formData.schoolDTOList.length - 1 : 0;
            setSchoolKeys(getArrKeys(formData.schoolDTOList));
            form.setFieldsValue({
                schoolKeys: getArrKeys(formData.schoolDTOList)
            });
        }
        if (formData.trainDTOList && formData.trainDTOList.length) {
            initTrainKey = formData.trainDTOList.length > 0 ? formData.trainDTOList.length - 1 : 0;
            setTrainKeys(getArrKeys(formData.trainDTOList));
            form.setFieldsValue({
                trainKeys: getArrKeys(formData.trainDTOList)
            });
        }
        if (formData.awardDTOList && formData.awardDTOList.length) {
            initAwardKey = formData.awardDTOList.length > 0 ? formData.awardDTOList.length - 1 : 0;
            setAwardKeys(getArrKeys(formData.awardDTOList));
            form.setFieldsValue({
                awardKeys: getArrKeys(formData.awardDTOList)
            });
        }
    }, [form, formData]);

    const computedValidLength = (removedIdsStr, keys) => {
        const removeId = form.getFieldValue(removedIdsStr);
        return keys.length - removeId.length;
    };

    const showErrorMessage = () => {
        message.error('至多添加10个');
    };

    // eslint-disable-next-line consistent-return
    const addFormList = type => {
        if (type === 'family') {
            if (computedValidLength('removeFamilyIds', familyKeys) >= 10) {
                return showErrorMessage();
            }
            initFamilyKey += 1;
            familyKeys.push(initFamilyKey);
            setFamilyKeys([...familyKeys]);
            form.setFieldsValue({
                familyKeys
            });
        } else if (type === 'work') {
            if (computedValidLength('removeWorkIds', workKeys) >= 10) {
                return showErrorMessage();
            }
            initWorkKey += 1;
            workKeys.push(initWorkKey);
            setWorkKeys([...workKeys]);
            form.setFieldsValue({
                workKeys
            });
        } else if (type === 'school') {
            if (computedValidLength('removeSchoolIds', schoolKeys) >= 10) {
                return showErrorMessage();
            }
            initSchoolKey += 1;
            schoolKeys.push(initSchoolKey);
            setSchoolKeys([...schoolKeys]);
            form.setFieldsValue({
                schoolKeys
            });
        } else if (type === 'train') {
            if (computedValidLength('removeTrainIds', trainKeys) >= 10) {
                return showErrorMessage();
            }
            initTrainKey += 1;
            trainKeys.push(initTrainKey);
            setTrainKeys([...trainKeys]);
            form.setFieldsValue({
                trainKeys
            });
        } else if (type === 'award') {
            if (computedValidLength('removeAwardIds', awardKeys) >= 10) {
                return showErrorMessage();
            }
            initAwardKey += 1;
            awardKeys.push(initAwardKey);
            setAwardKeys([...awardKeys]);
            form.setFieldsValue({
                awardKeys
            });
        }
    };
    // 删除组件
    const deleteGroup = (type, targetKey, deleteId) => {
        let newKeys = [];
        if (type === 'family') {
            if (deleteId) {
                // 删除的时候存储了这个id
                const removeId = [...removeFamilyIds, deleteId];
                setRemoveFamilyIds(removeId);
                form.setFieldsValue({
                    removeFamilyIds: removeId
                });
                return;
            }
            newKeys = familyKeys.filter(key => key !== targetKey);
            setFamilyKeys([...newKeys]);
            form.setFieldsValue({
                familyKeys: newKeys
            });
        } else if (type === 'work') {
            if (deleteId) {
                const removeId = [...removeWorkIds, deleteId];
                setRemoveWorkIds(removeId);
                form.setFieldsValue({
                    removeWorkIds: removeId
                });
                return;
            }
            newKeys = workKeys.filter(key => key !== targetKey);
            setWorkKeys([...newKeys]);
            form.setFieldsValue({
                workKeys: newKeys
            });
        } else if (type === 'school') {
            if (deleteId) {
                const removeId = [...removeSchoolIds, deleteId];
                setRemoveSchoolIds(removeId);
                form.setFieldsValue({
                    removeSchoolIds: removeId
                });
                return;
            }
            newKeys = schoolKeys.filter(key => key !== targetKey);
            setSchoolKeys([...newKeys]);
            form.setFieldsValue({
                schoolKeys: newKeys
            });
        } else if (type === 'train') {
            if (deleteId) {
                const removeId = [...removeTrainIds, deleteId];
                setRemoveTrainIds(removeId);
                form.setFieldsValue({
                    removeTrainIds: removeId
                });
                return;
            }
            newKeys = trainKeys.filter(key => key !== targetKey);
            setTrainKeys([...newKeys]);
            form.setFieldsValue({
                trainKeys: newKeys
            });
        } else if (type === 'award') {
            if (deleteId) {
                const removeId = [...removeAwardIds, deleteId];
                setRemoveAwardIds(removeId);
                form.setFieldsValue({
                    removeAwardIds: removeId
                });
                return;
            }
            newKeys = awardKeys.filter(key => key !== targetKey);
            setAwardKeys([...newKeys]);
            form.setFieldsValue({
                awardKeys: newKeys
            });
        }
    };
    // 月份弹窗关闭事件
    const handlePanelChange = (value, fileName) => {
        form.setFieldsValue({
            [fileName]: value
        });
    };
    const returnAreaCode = areaCode => {
        if (areaCode === '' || areaCode === undefined) {
            return returnDefinedAreaCode();
        }
        return areaCode;
    };
    // 传入类型，返回组件 子组件公用
    const getComponent = (type, code, fileName, placeholder, areaCode) => {
        if (type === 'input') {
            return <Input placeholder={placeholder} disabled={isDisabled} />;
        }
        if (type === 'time') {
            return (
                <RangePicker
                    disabled={isDisabled}
                    mode={['month', 'month']}
                    onPanelChange={value => {
                        handlePanelChange(value, fileName);
                    }}
                    format="YYYY-MM"
                />
            );
        }
        if (type === 'time2') {
            return <MonthPicker style={{ width: '100%' }} disabled={isDisabled} />;
        }
        if (type === 'select') {
            return (
                <Select placeholder={placeholder} disabled={isDisabled}>
                    {dict[code] &&
                        dict[code].map(item => (
                            <Option value={item.dictValue} key={item.dictValue}>
                                {item.dictName}
                            </Option>
                        ))}
                </Select>
            );
        }
        if (type === 'radio') {
            if (code === 'liveTogether') {
                return (
                    <Radio.Group disabled={isDisabled}>
                        {dict[code] &&
                            dict[code].map(item => (
                                <Radio value={item.dictValue} key={item.dictValue}>
                                    {item.dictName}
                                </Radio>
                            ))}
                    </Radio.Group>
                );
            }
            return '';
        }
        if (type === 'tel') {
            return (
                <Input
                    disabled={isDisabled}
                    placeholder="请填入手机号"
                    addonBefore={getFieldDecorator(`${fileName.split('_')[0]}_areaCode_${fileName.split('_')[2]}`, {
                        initialValue: returnAreaCode(areaCode)
                    })(
                        <Select placeholder="区号" place style={{ width: 80 }} disabled={isDisabled}>
                            <Option value="86">+86</Option>
                            <Option value="65">+65</Option>
                        </Select>
                    )}
                />
            );
        }
        return '';
    };

    // 因为一些日期字段需要特殊处理，返回默认参数
    const returnValue = (fileName, value) => {
        if (fileName === 'work_startTime' || fileName === 'school_startTime' || fileName === 'train_startTime') {
            if (value.startTime === '' && value.endTime === '') {
                return [];
            }
            return [
                value.startTime === '' ? undefined : moment(value.startTime),
                value.endTime === '' ? undefined : moment(value.endTime)
            ];
        }
        if (fileName === 'award_awardTime') {
            return value[map[fileName]] === '' ? undefined : moment(value[map[fileName]]);
        }
        return value[map[fileName]];
    };
    // 渲染表单组件
    const renderFormItem = type => {
        let arr = [];
        let keys = [];
        let value = [];
        let removeIds = [];
        if (type === 'family') {
            arr = jsonFormFamily;
            keys = familyKeys;
            value = formData.familyDTOList || [];
            removeIds = removeFamilyIds;
        } else if (type === 'work') {
            arr = jsonFormWork;
            keys = workKeys;
            value = formData.workDTOList || [];
            removeIds = removeWorkIds;
        } else if (type === 'school') {
            arr = jsonFormSchool;
            keys = schoolKeys;
            value = formData.schoolDTOList || [];
            removeIds = removeSchoolIds;
        } else if (type === 'train') {
            arr = jsonFormTrain;
            keys = trainKeys;
            value = formData.trainDTOList || [];
            removeIds = removeTrainIds;
        } else if (type === 'award') {
            arr = jsonFormAward;
            keys = awardKeys;
            value = formData.awardDTOList || [];
            removeIds = removeAwardIds;
        }

        return keys
            .filter(key => !removeIds.includes(value[key] && value[key].id))
            .map(key => (
                <div className={styles.block} key={type + key}>
                    {key !== 0 ? (
                        <i
                            className={cn(styles.del, 'iconfont icongms_list_icon_fail_default')}
                            onClick={() => {
                                deleteGroup(type, key, value[key] && value[key].id);
                            }}
                        />
                    ) : (
                        ''
                    )}
                    <FormContainer>
                        {arr.map(list => (
                            <Form.Item label={list.label} key={list.fileName} {...formItemLayout}>
                                {getFieldDecorator(`${list.fileName}_${key}`, {
                                    rules: list.rules,
                                    initialValue: value[key] && returnValue(list.fileName, value[key])
                                })(
                                    getComponent(
                                        list.type,
                                        list.code,
                                        `${list.fileName}_${key}`,
                                        list.placeholder,
                                        value[key] && value[key].areaCode
                                    )
                                )}
                            </Form.Item>
                        ))}
                    </FormContainer>
                </div>
            ));
    };
    return (
        <div>
            <div className={styles.item}>
                <Divider style={{ margin: '32px 0' }} />
                <div className={styles.addFormListWrap}>
                    <div className={styles.orgEditInfoTitle}>紧急联系人</div>
                    <FormContainer>
                        <Form.Item label="姓名" {...formItemLayout}>
                            {getFieldDecorator('emergencyContact', {
                                initialValue: userCode ? formData.emergencyContact : null,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入紧急联系人姓名'
                                    },
                                    {
                                        min: 2,
                                        max: 50,
                                        message: '请输入2~50个字符'
                                    },
                                    {
                                        pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                        message: '此处不能输入空格'
                                    }
                                ]
                            })(<Input placeholder="请输入紧急联系人姓名" disabled={isDisabled} />)}
                        </Form.Item>
                        <Form.Item label="与本人关系" {...formItemLayout}>
                            {getFieldDecorator('emergencyRelationship', {
                                initialValue:
                                    formData.emergencyRelationship === '' ? undefined : formData.emergencyRelationship,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择与本人关系'
                                    }
                                ]
                            })(
                                <Select placeholder="请选择与本人关系" disabled={isDisabled}>
                                    {dict.emergencyRelationship &&
                                        dict.emergencyRelationship.map(item => (
                                            <Option value={item.dictValue} key={item.dictValue}>
                                                {item.dictName}
                                            </Option>
                                        ))}
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item label="联系电话" {...formItemLayout}>
                            {getFieldDecorator('emergencyTelephone', {
                                initialValue: userCode ? formData.emergencyTelephone : null,
                                rules: [
                                    {
                                        required: true,
                                        validator(rule, value, callback) {
                                            const regex = /^\d{7,11}$/;
                                            if (!value) {
                                                callback('手机号不能为空');
                                            } else if (!regex.test(value)) {
                                                callback('只能输入7-11位数字');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <Input
                                    disabled={isDisabled}
                                    placeholder="请填入手机号"
                                    addonBefore={getFieldDecorator('emergencyAreaCode', {
                                        initialValue:
                                            formData.emergencyAreaCode === ''
                                                ? returnDefinedAreaCode()
                                                : formData.emergencyAreaCode
                                    })(
                                        <Select placeholder="区号" place style={{ width: 80 }} disabled={isDisabled}>
                                            <Option value="86">+86</Option>
                                            <Option value="65">+65</Option>
                                        </Select>
                                    )}
                                />
                            )}
                        </Form.Item>
                    </FormContainer>
                </div>
            </div>
            <Divider />
            <div className={styles.addFormListWrap}>
                <div className={styles.item}>
                    <div className={styles.orgEditInfoTitle}>家庭成员</div>
                    {renderFormItem('family')}
                    {isDisabled ? (
                        ''
                    ) : (
                        <div
                            className={styles.add}
                            onClick={() => {
                                addFormList('family');
                            }}
                        >
                            +添加家庭成员
                        </div>
                    )}
                </div>
                <div className={styles.item}>
                    <div className={styles.orgEditInfoTitle}>工作信息</div>
                    <Form.Item label="工作经验" {...formItemLayout2}>
                        {getFieldDecorator('workExperience', {
                            rules: [
                                {
                                    required: true,
                                    message: '请输入请选择工作经验'
                                }
                            ],
                            initialValue: formData.workExperience
                        })(
                            <Radio.Group disabled={isDisabled}>
                                <Radio value={1}>有</Radio>
                                <Radio value={0}>无(应届生)</Radio>
                            </Radio.Group>
                        )}
                    </Form.Item>
                    {Number(form.getFieldValue('workExperience')) === 1 ? (
                        <Fragment>
                            {renderFormItem('work')}
                            {isDisabled ? (
                                ''
                            ) : (
                                <div
                                    className={styles.add}
                                    onClick={() => {
                                        addFormList('work');
                                    }}
                                >
                                    +添加工作信息
                                </div>
                            )}
                        </Fragment>
                    ) : (
                        ''
                    )}
                </div>
                <div className={styles.item}>
                    <div className={styles.orgEditInfoTitle}>教育经历</div>
                    {renderFormItem('school')}
                    {isDisabled ? (
                        ''
                    ) : (
                        <div
                            className={styles.add}
                            onClick={() => {
                                addFormList('school');
                            }}
                        >
                            +添加教育经历
                        </div>
                    )}
                </div>
                <div className={styles.item}>
                    <div className={styles.orgEditInfoTitle}>培训经历</div>
                    {renderFormItem('train')}
                    {isDisabled ? (
                        ''
                    ) : (
                        <div
                            className={styles.add}
                            onClick={() => {
                                addFormList('train');
                            }}
                        >
                            +添加培训经历
                        </div>
                    )}
                </div>
                <div className={styles.item}>
                    <div className={styles.orgEditInfoTitle}>获奖记录</div>
                    {renderFormItem('award')}
                    {isDisabled ? (
                        ''
                    ) : (
                        <div
                            className={styles.add}
                            onClick={() => {
                                addFormList('award');
                            }}
                        >
                            +添加获奖记录
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};
export default AddForm;
